package com.swak.im;

import java.lang.reflect.Method;

import com.swak.annotation.Context;
import com.swak.utils.StringUtils;

import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

/**
 * 代表一个 IM 实例
 * 
 * @author 618lf
 */
@Getter
@Setter
@Accessors(chain = true)
public class Im {

	private String id;
	private String name;
	private Object service;
	private Method executeMethod;
	private int parallel;
	private int weight;
	private boolean opened;

	static Im create(ImConfig config, com.swak.annotation.im.DistributedIm im, Object jobService, Method executeMethod) {

		/*
		 * 确定任务唯一标识
		 */
		String id = StringUtils.isBlank(im.id()) ? jobService.getClass().getSimpleName() : im.id();

		/*
		 * 确定任务并行度
		 */
		int parallel = im.parallel();
		if (im.context() == Context.Concurrent) {
			parallel = parallel <= 0 ? config.getWorkerPoolSize() / 2 : parallel;
		} else if (im.context() == Context.Order) {
			parallel = parallel <= 0 ? 1 : parallel;
		} else {
			parallel = 1;
		}
		if ((im.context() == Context.Concurrent || im.context() == Context.Order)
				&& StringUtils.isNotBlank(im.pool())) {
			parallel = parallel <= 0 ? im.workers() / 2 : parallel;
		}

		return new Im().setId(id).setName(im.name()).setParallel(parallel).setService(jobService)
				.setExecuteMethod(executeMethod).setWeight(im.weight()).setOpened(im.opened());
	}
}
